package jpa.controller;

import com.querydsl.core.types.Predicate;
import jpa.entity.User;
import jpa.repository.PersonRepository;
import jpa.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.querydsl.binding.QuerydslPredicate;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.hateoas.EntityLinks;
import org.springframework.hateoas.PagedResources;
import org.springframework.hateoas.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by barton on 16-5-9.
 */
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserRepository ur;

    @Autowired
    private EntityLinks entityLinks;

    @Autowired
    private PersonRepository pr;

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public ResponseEntity<User> showUserForm(@PathVariable("id") User user, HttpServletRequest
            request) {
        System.out.println(request.getQueryString());
        String[] conditions = request.getParameterMap().get("condition");
        Map<String, Object> params = WebUtils.getParametersStartingWith(request, "SC_");
        for (String condition : conditions) {
            System.out.println(condition);
        }
        System.out.println(request.getParameterNames());
        return new ResponseEntity<>(user, HttpStatus.OK);
    }

    @RequestMapping(value = "querydsl", method = RequestMethod.GET)
    public ResponseEntity<Page<User>> querydslWeb(
            @QuerydslPredicate(root = User.class) Predicate predicate,
            Pageable pageable, @RequestParam MultiValueMap<String, String> params) {
        return new ResponseEntity<>(ur.findAll(predicate, pageable), HttpStatus.OK);
    }

    @RequestMapping(value = "", method = RequestMethod.GET)
    @ResponseBody
    public HttpEntity<Resource<User>> users(String id) {
        User user = ur.findOne(Long.valueOf(id));
        Resource<User> resource = new Resource<>(user);
        resource.add(this.entityLinks.linkToSingleResource(User.class, id));
        return new ResponseEntity<>(resource, HttpStatus.OK);
    }
}
